﻿using Autofac;
using DesignByContract;

namespace MadMediaManager.Core.DependencyInjectionSupport
{
    public static class AppServiceContainer
    {
        private static bool _hasBeenInitializaed;
        private static IContainer _container;

        public static void Init(IContainerConfigurator<IContainer> configurator)
        {
            Check.Require(configurator != null, "configurator cannot be null");

            if (_hasBeenInitializaed)
            {
                RemoveConfiguration();
            }

            _container = configurator.Build();
            _hasBeenInitializaed = true;
        }

        public static void RemoveConfiguration()
        {
            if (_container != null)
            {
                _container.Dispose();
            }
            _container = null;
            _hasBeenInitializaed = false;
        }

        public static TRegistered Get<TRegistered>()
        {
            return _container.Resolve<TRegistered>();
        }

        public static TRegistered Get<TRegistered>(string name)
        {
            return _container.ResolveNamed<TRegistered>(name);
        }
    }
}
